﻿using System;
using System.ComponentModel;
using System.Text.RegularExpressions;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace MyLib.Web.UI {
	/// <summary>
	/// Paragraph
	/// </summary>
	[DefaultProperty("Text")]
	[ToolboxData("<{0}:MyPara runat=server></{0}:MyPara>")]
	public class MyPara : WebControl, ITextControl {
		/// <summary>
		/// 
		/// <para>2 - Caption, 3 - Url</para>
		/// </summary>
		private static readonly Regex EXTERNAL_LINK =
			new Regex(@"\[\[(([\w\.]+)\|)?(mailto\:|(news|(ht|f)tp(s?))\://\S+)\]\]",
				RegexOptions.Compiled | RegexOptions.Singleline);

		/// <summary>
		/// 
		/// </summary>
		[Bindable(BindableSupport.Yes, BindingDirection.OneWay)]
		[Localizable(true)]
		[Category("Appearance")]
		[DefaultValue("")]
		[PersistenceMode(PersistenceMode.InnerDefaultProperty)]
		public string Text {
			get;
			set;
		}

		/// <summary>
		/// 
		/// </summary>
		/// <param name="writer"></param>
		public override void RenderBeginTag(HtmlTextWriter writer) {
			AddAttributesToRender(writer);
			writer.AddStyleAttribute("word-wrap", "break-word");
			writer.AddStyleAttribute(HtmlTextWriterStyle.Overflow, "hidden");
			writer.RenderBeginTag(HtmlTextWriterTag.P);
		}

		/// <summary>
		/// 
		/// </summary>
		/// <param name="writer"></param>
		public override void RenderEndTag(HtmlTextWriter writer) {
			writer.RenderEndTag();
		}

		/// <summary>
		/// 
		/// </summary>
		/// <param name="writer"></param>
		protected override void RenderContents(HtmlTextWriter writer) {
			if (!string.IsNullOrWhiteSpace(Text)) {
				var lines = Text.Split('\n');
				var l = lines.Length;
				for (int i = 0; i < l; ++i) {
					var line = lines[i];

					var pp = 0;
					foreach (Match m in EXTERNAL_LINK.Matches(line)) {
						writer.WriteEncodedText(
							line.Substring(pp, m.Index - pp));
						pp = m.Index + m.Length;

						if (!m.Success) {
							writer.WriteEncodedText(m.Value);
						} else {
							var title = m.Groups[2].Value;
							var url = m.Groups[3].Value;

							if (string.IsNullOrEmpty(title))
								title = url;

							writer.AddAttribute(HtmlTextWriterAttribute.Href, url);
							writer.AddAttribute(HtmlTextWriterAttribute.Target, "_new");
							writer.AddAttribute("ext", "1");
							writer.RenderBeginTag(HtmlTextWriterTag.A);
							writer.WriteEncodedText(title.AbbreviatedTo());
							writer.RenderEndTag();
						}
					}

					if (pp < line.Length) {
						writer.WriteEncodedText(line.Substring(pp, line.Length - pp));
					}

					if (i < l - 1)
						writer.Write("<br />");
				}
			} else {
				writer.Write(" &nbsp; ");
				// writer.WriteEncodedText(Text);
			}
		}
	} // end of MyPara.
}
